package com.zhangtai.modules.controller.admin;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.PerformanceRatioDao;
import com.zhangtai.modules.dao.PerformanceUnitManagementDao;
import com.zhangtai.modules.dao.PerformanceUnitRecordDao;
import com.zhangtai.modules.dto.PerformanceUnitManagementDto;
import com.zhangtai.modules.entity.performance.PerformanceRatioEntity;
import com.zhangtai.modules.entity.performance.PerformanceUnitManagementEntity;
import com.zhangtai.modules.entity.performance.PerformanceUnitRecordEntity;
import com.zhangtai.modules.entity.system.UserEntity;
import com.zhangtai.modules.service.performance.PerformanceRatioService;
import com.zhangtai.modules.service.performance.PerformanceUnitManagementService;
import com.zhangtai.modules.service.performance.PerformanceUnitRecordService;
import com.zhangtai.modules.service.system.UserService;
import com.zhangtai.modules.vo.PerformanceRatioVo;
import com.zhangtai.modules.vo.PerformanceUnitManagementVo;
import com.zhangtai.modules.vo.PerformanceUnitRecordVo;
import com.zhangtai.modules.vo.PerformanceUnitVo;
import com.zhangtai.utils.BeanUtilsMabach;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import com.zhangtai.utils.SnowflakeIdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;


/**
 * 绩效
 *
 */
@RestController
@Api(tags="员工绩效接口")
@RequestMapping("performance")
@Slf4j
public class PerformanceController {
    @Autowired
    private PerformanceRatioService performanceRatioService;
    @Autowired
    private PerformanceRatioDao performanceRatioDao;
    @Autowired
    private PerformanceUnitRecordService performanceUnitRecordService;
    @Autowired
    private PerformanceUnitRecordDao performanceUnitRecordDao;
    @Autowired
    private LoginController loginController;
    @Autowired
    private UserService userService;
    @Autowired
    private JobController jobController;
    @Autowired
    private PerformanceUnitManagementService performanceUnitManagementService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private DimissionController dimissionController;
    @Autowired
    private PerformanceUnitManagementDao performanceUnitManagementDao;
    /**
     * 列表
     */
    @GetMapping("/getPerformanceRatioPage")
    @ApiOperation(value="分页查询个人单位绩效占比")
    public R getPerformanceRatioPage(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                     HttpServletRequest request){
        PageResult result= performanceRatioService.queryPage(null,pageNum,pageSize);
        return R.ok(result);
    }

    @GetMapping("/getPerformanceUnitRecordPage")
    @ApiOperation(value="分页查询单位绩效记录列表")
    public R getPerformanceUnitRecordPage(@RequestParam(value = "assessmentYear", required = false) String assessmentYear,
                                          @RequestParam(value = "name",  required = false) String name,
                                          @RequestParam(value = "assessmentCycle",  required = false) Integer assessmentCycle,
                                          @RequestParam(value = "performanceName",  required = false) String performanceName,
                                          @RequestParam(value = "type",  defaultValue = "1") Integer type,
                                          @RequestParam(value = "approveStatus", required = false) List<Integer> approveStatus,
                                          @RequestParam(value = "status", required = false) Integer status,
                                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                     HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        PageResult result= performanceUnitRecordService.queryPage(orgIds,performanceName,assessmentYear,name,assessmentCycle,type,approveStatus,status,pageNum,pageSize);
        return R.ok(result);
    }

    @GetMapping("/getPerformanceUnitManagementPage")
    @ApiOperation(value="分页查询单位绩效管理列表")
    public R getPerformanceUnitManagementPage(@RequestParam(value = "assessmentYear", required = false) String assessmentYear,
                                          @RequestParam(value = "name",  required = false) String    name,
                                          @RequestParam(value = "assessmentCycle",  required = false) Integer assessmentCycle,
                                              @RequestParam(value = "performanceName",  required = false) String performanceName,
                                              @RequestParam(value = "approveStatus", required = false) List<Integer> approveStatus,
                                              @RequestParam(value = "status", required = false) Integer status,
                                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                          HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        PageResult result= performanceUnitManagementService.queryPage(orgIds,assessmentYear,name,assessmentCycle,performanceName,approveStatus,status,pageNum,pageSize);
        if(!CollectionUtils.isEmpty(result.getList())) {
            List<PerformanceUnitManagementDto> performanceUnitManagementDtoList=new ArrayList<>();
            List<PerformanceUnitManagementEntity> performanceUnitManagementEntityList = result.getList();
            for (PerformanceUnitManagementEntity performanceUnitManagementEntity : performanceUnitManagementEntityList) {
                PerformanceUnitManagementDto performanceUnitManagementDto = BeanUtilsMabach.doToDto(performanceUnitManagementEntity, PerformanceUnitManagementDto.class);
                List<PerformanceUnitRecordEntity> performanceUnitRecordEntityList= performanceUnitRecordDao.selectList(new QueryWrapper<PerformanceUnitRecordEntity>().eq("programme_id",performanceUnitManagementDto.getId()));
                JSONArray orgId=new JSONArray();
                for(PerformanceUnitRecordEntity performanceUnitRecordEntity:performanceUnitRecordEntityList){
                    JSONObject obj=new JSONObject();
                    obj.put("orgId",performanceUnitRecordEntity.getOrgId());
                    obj.put("performanceLevel",performanceUnitRecordEntity.getPerformanceLevel());
                    orgId.add(obj);
                }
                performanceUnitManagementDto.setOrgIds(orgId);
                performanceUnitManagementDtoList.add(performanceUnitManagementDto);
            }
            result.setList(performanceUnitManagementDtoList);
        }
        return R.ok(result);
    }

    /**
     * 信息
     */
    @GetMapping("/getPerformanceUnitManagementById")
    @ApiOperation(value="根据id查询单位管理的单位")
    public R getPerformanceUnitManagementById(@RequestParam("id") String id){
       List<PerformanceUnitRecordEntity> performanceUnitRecordEntityList= performanceUnitRecordDao.selectList(new QueryWrapper<PerformanceUnitRecordEntity>().eq("programme_id",id));
       return R.ok(performanceUnitRecordEntityList);
    }

    /**
     * 信息
     */
    @GetMapping("/getPerformanceRatioById")
    @ApiOperation(value="根据id查询个人单位绩效占比")
    public R getPerformanceRatioById(@RequestParam("id") Long id){
		PerformanceRatioEntity performanceRatio = performanceRatioService.getByIdE(id);
        return R.ok(performanceRatio);
    }
    /**
     * 保存
     */
    @PostMapping("/saveAndUpdatePerformanceRatio")
    @ApiOperation(value="保存和修改个人单位绩效占比")
    public R saveAndUpdatePerformanceRatio(@RequestBody  @Valid PerformanceRatioVo performanceRatioVo){

        PerformanceRatioEntity performanceRatioEntity= BeanUtilsMabach.doToDto(performanceRatioVo,PerformanceRatioEntity.class);
        PerformanceRatioEntity performanceRatio = performanceRatioService.getByIdE(performanceRatioVo.getId());
        if(ObjectUtils.isEmpty( performanceRatio)){
            performanceRatioDao.insert(performanceRatioEntity);
        }else {
            performanceRatioService.updateByIdE(performanceRatioEntity);
        }
        return R.ok();
    }

    @PostMapping("/saveAndUpdatePerformanceUnitRecord")
    @ApiOperation(value="保存和修改单位绩效记录")
    @SysAuthorityLog("保存和修改单位绩效记录")
    @Transactional
    public R saveAndUpdatePerformanceUnitRecord(@RequestBody  @Valid PerformanceUnitRecordVo performanceUnitRecordVo, HttpServletRequest request) throws Exception {
        JSONObject data = loginController.getUserInfo(request).getData();//只能查询自己的信息
        if (ObjectUtils.isEmpty(data)){
            return R.error("请先登录");
        }
        Long id=data.getLong("id");
        PerformanceUnitRecordEntity performanceUnitRecordEntity= BeanUtilsMabach.doToDto(performanceUnitRecordVo, PerformanceUnitRecordEntity.class);
        performanceUnitRecordEntity.setOrgName(jobController.getOrgNameById(performanceUnitRecordVo.getOrgId()));
        UserEntity applyEmp=userService.getByIdE(id);
        performanceUnitRecordEntity.setName(applyEmp.getName());
        performanceUnitRecordEntity.setCode(applyEmp.getUsercode());
        if(performanceUnitRecordVo.getId()==null){
            performanceUnitRecordEntity.setType(2); //这个接口只能新建月度
            performanceUnitRecordService.saveE(performanceUnitRecordEntity);
        }else {
            performanceUnitRecordService.updateByIdE(performanceUnitRecordEntity);
        }
        return R.ok();
    }

    @PostMapping("/saveAndUpdatePerformanceUnitManagement")
    @ApiOperation(value="保存和修改单位绩效管理")
    @SysAuthorityLog("保存和修改单位绩效管理")
    @Transactional
    public R saveAndUpdatePerformanceUnitManagement(@RequestBody  @Valid PerformanceUnitManagementVo performanceUnitManagementVo, HttpServletRequest request) throws Exception {
        JSONObject data = loginController.getUserInfo(request).getData();//只能查询自己的信息
        if (ObjectUtils.isEmpty(data)){
            return R.error("请先登录");
        }
        PerformanceUnitManagementEntity performanceUnitManagementEntity= BeanUtilsMabach.doToDto(performanceUnitManagementVo, PerformanceUnitManagementEntity.class);
        UserEntity applyEmp=userService.getByIdE(data.getLong("id"));
        performanceUnitManagementEntity.setName(applyEmp.getName());
        performanceUnitManagementEntity.setCode(applyEmp.getUsercode());
        performanceUnitManagementEntity.setUnit_id(applyEmp.getDepId());
        performanceUnitManagementEntity.setFileUrl(dimissionController.ListToString(performanceUnitManagementVo.getFileUrlList()));
        if(performanceUnitManagementVo.getId()==null){
            long id = snowflakeIdWorker.nextId();
            performanceUnitManagementEntity.setId(id);
            performanceUnitManagementService.saveE(performanceUnitManagementEntity);
        }else {
            performanceUnitRecordDao.delete(new QueryWrapper<PerformanceUnitRecordEntity>().eq("programme_id",performanceUnitManagementEntity.getId()));
            performanceUnitManagementService.updateByIdE(performanceUnitManagementEntity);
        }
        if(!CollectionUtils.isEmpty(performanceUnitManagementVo.getPerformanceUnitVoArrayList())){
            for (PerformanceUnitVo performanceUnitVo:performanceUnitManagementVo.getPerformanceUnitVoArrayList()){
                PerformanceUnitRecordEntity performanceUnitRecordEntity=new PerformanceUnitRecordEntity();
                performanceUnitRecordEntity.setOrgId(performanceUnitVo.getOrgId());
                performanceUnitRecordEntity.setOrgName(jobController.getOrgNameById(performanceUnitVo.getOrgId()));
                performanceUnitRecordEntity.setPerformanceName(performanceUnitManagementEntity.getPerformanceName());
                performanceUnitRecordEntity.setAssessmentYear(performanceUnitManagementEntity.getAssessmentYear());
                performanceUnitRecordEntity.setAssessmentCycle(performanceUnitManagementEntity.getAssessmentCycle());
                performanceUnitRecordEntity.setProgrammeId(performanceUnitManagementEntity.getId());
                performanceUnitRecordEntity.setType(1);
                performanceUnitRecordEntity.setPerformanceLevel(performanceUnitVo.getPerformanceLevel());
                performanceUnitRecordService.saveE(performanceUnitRecordEntity);
            }

        }
        return R.ok();
    }
    @GetMapping("/getPerformanceUnitRecordByOrgIdAndYearList")
    @ApiOperation(value="根据年度 和公司orgid 获取 单位绩效成绩列表")
    public R getPerformanceUnitRecordByOrgIdAndYearList(@RequestParam (value = "orgIds") List<String> orgIds,@RequestParam (value = "assessmentYear") String assessmentYear) {
        JSONArray array=new JSONArray();
        if(!CollectionUtils.isEmpty(orgIds)){
            for(String orgId:orgIds){
              R r=  getPerformanceUnitRecordByOrgIdAndYear(orgId,assessmentYear);
                array.add(r.getData());
            }
        }
        return R.ok(array);
    }

    @GetMapping("/getPerformanceUnitRecordByOrgIdAndYear")
    @ApiOperation(value="根据年度 和公司orgid 获取 单位绩效成绩")
    public R getPerformanceUnitRecordByOrgIdAndYear(@RequestParam (value = "orgId") String orgId,@RequestParam (value = "assessmentYear") String assessmentYear){
        JSONObject jsonObject=new JSONObject();
        List<PerformanceUnitRecordEntity> QuarterList= performanceUnitRecordDao.selectList(new QueryWrapper<PerformanceUnitRecordEntity>()
              .eq("org_id",orgId).eq("assessment_year",assessmentYear).eq("type",1).orderByAsc("assessment_cycle"));
        JSONArray jsonArrayQuarter=new JSONArray();
        if(!CollectionUtils.isEmpty(QuarterList)){
            for (PerformanceUnitRecordEntity performanceUnitRecordEntity:QuarterList){
                switch (performanceUnitRecordEntity.getAssessmentCycle()){
                    case 1:
                        jsonArrayQuarter.add(getObj("firstQuarter","一季度",performanceUnitRecordEntity.getPerformanceLevel()));
                        break;
                    case 2:
                        jsonArrayQuarter.add(getObj("halfQuarter","半季度",performanceUnitRecordEntity.getPerformanceLevel()));
                        break;
                    case 3:
                        jsonArrayQuarter.add(getObj("thirdQuarter","三季度",performanceUnitRecordEntity.getPerformanceLevel()));
                        break;
                    case 4:
                        jsonArrayQuarter.add(getObj("yearQuarter","年季度",performanceUnitRecordEntity.getPerformanceLevel()));
                        break;
                }
            }
        }
        jsonObject.put("quarter",jsonArrayQuarter);

        List<PerformanceUnitRecordEntity> monthList= performanceUnitRecordDao.selectList(new QueryWrapper<PerformanceUnitRecordEntity>()
                .eq("org_id",orgId).eq("assessment_year",assessmentYear).eq("type",2).orderByAsc("assessment_cycle"));
        JSONArray jsonArrayMonth=new JSONArray();
        if(!CollectionUtils.isEmpty(monthList)){
            for (PerformanceUnitRecordEntity performanceUnitRecordEntity:monthList){
                switch (performanceUnitRecordEntity.getAssessmentCycle()){
                    case 1:
                        jsonArrayMonth.add(getObj("monthOne","1月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 2:
                        jsonArrayMonth.add(getObj("monthTwo","2月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 3:
                        jsonArrayMonth.add(getObj("monthThree","3月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 4:
                        jsonArrayMonth.add(getObj("monthFour","4月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 5:
                        jsonArrayMonth.add(getObj("monthFive","5月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 6:
                        jsonArrayMonth.add(getObj("monthSix","6月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 7:
                        jsonArrayMonth.add(getObj("monthSeven","7月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 8:
                        jsonArrayMonth.add(getObj("monthEight","8月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 9:
                        jsonArrayMonth.add(getObj("monthNine","9月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 10:
                        jsonArrayMonth.add(getObj("monthTen","10月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 11:
                        jsonArrayMonth.add(getObj("monthEleven","11月",performanceUnitRecordEntity.getScore()+""));
                        break;
                    case 12:
                        jsonArrayMonth.add(getObj("monthTwelve","12月",performanceUnitRecordEntity.getScore()+""));
                        break;
                }
            }
        }
        jsonObject.put("month",jsonArrayMonth);
        jsonObject.put("orgName",jobController.getOrgNameById(Long.valueOf(orgId)));
        jsonObject.put("orgId",orgId);
        return R.ok(jsonObject);

    }

    @DeleteMapping("/deletePerformanceUnitRecordById")
    @ApiOperation(value="删除单位绩效记录")
    public R deletePerformanceUnitRecordById(@RequestParam("id") String id){
             performanceUnitRecordDao.deleteById(id);
        return R.ok();
    }

    @DeleteMapping("/deletePerformanceUnitManagementById")
    @ApiOperation(value="删除单位绩效管理")
    public R deletePerformanceUnitManagementById(@RequestParam("id") String id){
        performanceUnitManagementDao.deleteById(id);
        performanceUnitRecordDao.delete(new QueryWrapper<PerformanceUnitRecordEntity>().eq("programme_id",id));
        return R.ok();
    }
     public Object getObj(String name,String title,String value){
         JSONObject object=new JSONObject();
//         object.put("title",name);
//         object.put(name,title);
//         object.put("value",value);
           object.put(name,value);
         return object;
     }

}
